﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Newtonsoft.Json;
using JHStock.Update;
using Tools;
using System.Text.RegularExpressions;

namespace JHStock
{	
	[JsonObject(MemberSerialization.OptOut)]
    public class JSConfig
    {   
        public JSConfig()
        {
        	pathconfig = new PathConfig();
        	staticsconfig = new StaticsConfig();
            _LoadReady = false;
        	_filename = "";
        }       
        public void Load(string filename){
        	this._filename = filename;
        	string str = File.ReadAllText(filename);
        	JSConfig jc = JsonConvert.DeserializeObject<JSConfig>(str);
        	this.pathconfig  = jc.pathconfig;
        	this.staticsconfig = jc.staticsconfig;
            this.Memostr = jc.Memostr;
            _LoadReady = false;
            if(pathconfig.szpath!=null && pathconfig.shpath!=null && pathconfig.dbpath!=null
                && File.Exists(pathconfig.dbpath) &&Directory.Exists(pathconfig.szpath) && Directory.Exists( pathconfig.shpath))
            _LoadReady = true;
        }
        public void Save(string tfilename = "")
        {
        	string str = JsonFormatTool.ConvertJsonString( JsonConvert.SerializeObject(this) );
            if(tfilename == "")
                File.WriteAllText(_filename, str);
            else            	
                File.WriteAllText(tfilename, str);
        }
        public bool CheckPath()
        {
            if (_LoadReady)
            {
                if (!pathconfig .CheckWorkPath())
                    throw new Exception("工作目录不存在，请手工创建" + pathconfig.NowWorkPath());
                return true;
            }
            return false;
        }
        public int GetUrlDaysCount(string kdatatype)
        {
            string input = string.Join("|", Memostr);
            Regex r = new Regex("\\|" + kdatatype + "-([0-9]*)\\|");
            Match m = r.Match(input);
            if (m.Success)
                return Convert.ToInt32(m.Groups[1].Value);
            return staticsconfig.KDataDaysCount;
        }
        public PathConfig pathconfig {get;set;}       
        public StaticsConfig staticsconfig {get;set;}
        public List<string> Memostr { get; set; }      
        
        [JsonIgnore]
        private string _filename;
        [JsonIgnore]
        private bool _LoadReady;


        public JSConfig Clone(string path)
        {
            JSConfig js = new JSConfig();
            js._filename = _filename;
            js._LoadReady = _LoadReady;
            js.Memostr = Memostr;
            js.pathconfig = pathconfig.Clone(path);
            js.staticsconfig = staticsconfig;          
            return js;
        }
    }    
}
